<script lang="ts" setup>
import { reactive, watch } from "vue";
import iconfont from "@/assets/images/iconfont.json";
import type { AutocompleteFetchSuggestionsCallback } from "element-plus";
import IconSymbol from "./icon-symbol.vue";

const state = reactive<{ value: string; disabled: boolean }>({ value: "", disabled: false });
const props = withDefaults(defineProps<{ modelValue: string; disabled?: boolean }>(), { modelValue: "", disabled: false });
const emits = defineEmits(["update:modelValue"]);
const icons = iconfont.glyphs.map((g) => g.font_class);

watch(
  () => props.modelValue,
  (newVal) => (state.value = newVal),
  { immediate: true },
);

watch(
  () => props.disabled,
  (newVal) => (state.disabled = newVal),
  { immediate: true },
);

function fetchSuggestions(keyword: string, cb: AutocompleteFetchSuggestionsCallback) {
  const result = icons
    .filter((i) => i.indexOf(keyword) > -1)
    .slice(0, 10)
    .map((i) => ({ value: i }));
  cb(result);
}

function handleSelect(record: Record<string, any>) {
  emits("update:modelValue", record.value);
}
</script>

<template>
  <el-autocomplete v-model="state.value" :fetch-suggestions="fetchSuggestions" :disabled="state.disabled" @select="handleSelect" placeholder="请输入图标关键字">
    <template #suffix><icon-symbol class="picker-suffix" :name="state.value" /></template>
    <template #default="{ item }">
      <icon-symbol :name="item.value" />
      <span v-text="item.value"></span>
    </template>
  </el-autocomplete>
</template>

<style lang="scss" scoped>
.picker-suffix {
  margin-right: 5px;
  height: 100%;
}
</style>
